package com.abiao.demo.util;


import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @program: start-build
 * @description: 转换工具
 * @author: luobiao
 * @date: 2022-02-12 09:41
 **/
public class ConversionUtil {
    public ConversionUtil() {
    }

    public static <T, R> R applyToJson(T t, Class<R> tClass) {
        return JSONObject.parseObject(JSONObject.toJSONString(t, new SerializerFeature[]{SerializerFeature.WriteMapNullValue}), tClass);
    }

    public static <T, R> R apply(T t, Class<R> tClass) {
        R r = null;

        try {
            r = tClass.newInstance();
            BeanUtils.copyProperties(t, r);
        } catch (Exception var4) {
            var4.printStackTrace();
        }

        return r;
    }

    public static <T, R> List<R> batchApply(List<T> list, Class<R> tClass) {
        return (List)(CollectionUtils.isEmpty(list) ? new ArrayList() : JSONObject.parseArray(JSONObject.toJSONString(list, new SerializerFeature[]{SerializerFeature.WriteMapNullValue}), tClass));
    }

    public static <T, R> List<R> batchApplyToArray(List<T> list, Class<R> tClass) {
        List<R> responseList = new ArrayList();
        if (!CollectionUtils.isEmpty(list)) {
            Iterator var3 = list.iterator();

            while(var3.hasNext()) {
                T t = (T)var3.next();
                responseList.add(apply(t, tClass));
            }
        }
        return responseList;
    }
}
